import paypalrestsdk
from django.http import HttpResponse
from django.shortcuts import redirect


def payment(request):

    paypalrestsdk.configure({
    "mode":"sandbox",
    "client_id":"AQ3fy0KvXKjuNPlBbZY40BxlFOxcjgPRIdagKIZYigDpCHRRe5RqvYtaZsMVqKD4JBMHx_Bv_BPBVZrf",
    "client_secret":"EEixqKvwkZbQKfP9N8R_qurjAYltwD4vFtB-_3M7vkwJ0bba5SUbQMnn8koNYMnfmv44Qt-lhzgEM5Gl"
    })

    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"},
        "redirect_urls": {
            "return_url": "http://127.0.0.1:8000/palpay/pay/",#支付成功跳转页面
            "cancel_url": "http://127.0.0.1:3000/paypal/cancel/"},#取消支付页面
        "transactions": [{
            "amount": {
                "total": "5.00",
                "currency": "USD"},
            "description": "这是一个订单测试"}]})

    if payment.create():
        print("Payment created successfully")
        for link in payment.links:
            if link.rel == "approval_url":
                approval_url = str(link.href)
                print("Redirect for approval: %s" % (approval_url))
                return redirect(approval_url)
    else:
        print(payment.error)
        return HttpResponse("支付失败")


def payment_execute(request):

    paymentid = request.GET.get("paymentId") #订单id
    payerid = request.GET.get("PayerID")  #支付者id

    payment = paypalrestsdk.Payment.find(paymentid)


    if payment.execute({"payer_id": payerid}):
        print("Payment execute successfully")
        return HttpResponse("支付成功")
    else:
        print(payment.error) # Error Hash
        return HttpResponse("支付失败")

